package com.example.lncd.ui;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;

import com.example.lncd.R;
import com.example.lncd.api.ApiService;
import com.example.lncd.api.RetrofitClient;
import com.example.lncd.model.User;
import com.example.lncd.ui.auth.LoginActivity;
import com.example.lncd.ui.elderly.ElderlyMainActivity;
import com.example.lncd.ui.family.FamilyMainActivity;
import com.example.lncd.util.PreferenceManager;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class RoleSelectionActivity extends AppCompatActivity {
    
    private static final String TAG = "RoleSelectionActivity";
    private CardView cardFamily, cardElderly;
    private TextView tvWelcome, tvSelectRole;
    private ProgressBar progressBar;
    private PreferenceManager preferenceManager;
    private ApiService apiService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_role_selection);
        
        // 初始化视图
        cardFamily = findViewById(R.id.cardFamily);
        cardElderly = findViewById(R.id.cardElderly);
        tvWelcome = findViewById(R.id.tvWelcome);
        tvSelectRole = findViewById(R.id.tvSelectRole);
        progressBar = findViewById(R.id.progressBar);
        
        if (progressBar == null) {
            // 如果布局中没有进度条，动态添加一个
            progressBar = new ProgressBar(this, null, android.R.attr.progressBarStyleLarge);
            progressBar.setVisibility(View.GONE);
        }
        
        // 初始化偏好管理器和API服务
        preferenceManager = new PreferenceManager(this);
        apiService = RetrofitClient.getApiService();
        
        // 显示用户名
        String username = preferenceManager.getUsername();
        if (username != null && !username.isEmpty()) {
            tvWelcome.setText("欢迎，" + username);
        }
        
        // 设置家人端卡片点击事件
        cardFamily.setOnClickListener(v -> {
            showProgress(true);
            updateUserTypeAndNavigate(User.UserType.FAMILY);
        });
        
        // 设置关爱端卡片点击事件
        cardElderly.setOnClickListener(v -> {
            showProgress(true);
            updateUserTypeAndNavigate(User.UserType.ELDERLY);
        });
        
        // 检查用户ID是否有效
        Long userId = preferenceManager.getUserId();
        Log.d(TAG, "用户ID: " + userId);
        if (userId == -1) {
            // 从Intent中获取用户ID
            Intent intent = getIntent();
            if (intent != null && intent.hasExtra("USER_ID")) {
                userId = intent.getLongExtra("USER_ID", -1);
                Log.d(TAG, "从Intent获取用户ID: " + userId);
                if (userId != -1) {
                    // 获取用户信息
                    getUserInfo(userId);
                }
            }
        }
    }
    
    private void getUserInfo(Long userId) {
        // 获取用户信息
        Call<User> getUserCall = apiService.getUserById(userId);
        getUserCall.enqueue(new Callback<User>() {
            @Override
            public void onResponse(Call<User> call, Response<User> response) {
                if (response.isSuccessful() && response.body() != null) {
                    User user = response.body();
                    Log.d(TAG, "获取用户信息成功: " + user.getUsername());
                    // 保存用户信息到本地
                    preferenceManager.saveUser(user);
                }
            }

            @Override
            public void onFailure(Call<User> call, Throwable t) {
                Log.e(TAG, "获取用户信息失败: " + t.getMessage());
            }
        });
    }
    
    private void showProgress(boolean show) {
        if (progressBar != null) {
            progressBar.setVisibility(show ? View.VISIBLE : View.GONE);
        }
        cardFamily.setEnabled(!show);
        cardElderly.setEnabled(!show);
    }
    
    private void updateUserTypeAndNavigate(User.UserType userType) {
        Long userId = preferenceManager.getUserId();
        Log.d(TAG, "更新用户类型，用户ID: " + userId);
        
        if (userId == -1) {
            showProgress(false);
            Toast.makeText(this, "用户信息错误，请重新登录", Toast.LENGTH_SHORT).show();
            // 跳转回登录页面
            Intent intent = new Intent(this, LoginActivity.class);
            startActivity(intent);
            finish();
            return;
        }
        
        // 直接使用用户ID创建新的User对象并设置类型
        User userToUpdate = new User();
        userToUpdate.setId(userId);
        userToUpdate.setUsername(preferenceManager.getUsername());
        userToUpdate.setUserType(userType);
        
        // 先本地保存类型
        preferenceManager.saveUser(userToUpdate);
        
        // 更新用户类型到服务器
        Call<User> updateCall = apiService.updateUser(userId, userToUpdate);
        updateCall.enqueue(new Callback<User>() {
            @Override
            public void onResponse(Call<User> call, Response<User> response) {
                showProgress(false);
                if (response.isSuccessful() && response.body() != null) {
                    User updatedUser = response.body();
                    Log.d(TAG, "服务器更新用户类型成功: " + updatedUser.getUserType());
                    
                    // 检查更新后的用户类型
                    if (updatedUser.getUserType() == null) {
                        Log.w(TAG, "服务器返回的userType为null，使用本地类型");
                        updatedUser.setUserType(userType); // 使用本地选择的类型
                    }
                    
                    // 保存更新后的用户信息
                    preferenceManager.saveUser(updatedUser);
                    
                    // 根据用户类型跳转到不同的主页
                    navigateToMainActivity(userType);
                } else {
                    Log.e(TAG, "服务器更新用户类型失败: " + (response.errorBody() != null ? response.errorBody().toString() : "未知错误"));
                    // 使用本地类型
                    navigateToMainActivity(userType);
                }
            }

            @Override
            public void onFailure(Call<User> call, Throwable t) {
                showProgress(false);
                Log.e(TAG, "网络请求失败: " + t.getMessage());
                Toast.makeText(RoleSelectionActivity.this, "网络错误，使用本地设置", Toast.LENGTH_SHORT).show();
                // 使用本地类型
                navigateToMainActivity(userType);
            }
        });
    }
    
    private void navigateToMainActivity(User.UserType userType) {
        if (userType == User.UserType.FAMILY) {
            navigateToFamilyMain();
        } else {
            navigateToElderlyMain();
        }
    }
    
    private void navigateToFamilyMain() {
        Intent intent = new Intent(this, FamilyMainActivity.class);
        startActivity(intent);
        finish();
    }
    
    private void navigateToElderlyMain() {
        Intent intent = new Intent(this, ElderlyMainActivity.class);
        startActivity(intent);
        finish();
    }
} 